import config from '@/common/config.js'

const util = {}

util.sleep = (delay = 1000) => new Promise((resolve) => setTimeout(resolve, delay))

util.setToken = (token) => uni.setStorageSync(config.tokenName, token)

util.getToken = () => uni.getStorageSync(config.tokenName)

util.removeToken = () => uni.removeStorageSync(config.tokenName)

/** 验证手机号码 */
util.validateMobile = (mobile) => /^1[3456789]\d{9}$/.test(mobile)

/** 退出登录或 token 过期要清除的数据在这里清除 */
util.logoutClear = () => {
  // 退出登录时 storage 里要保留的数据的 key
  const keyArr = [
    //
    // 'test',
  ]
  const obj = {}
  for (const index in keyArr) {
    obj[keyArr[index]] = uni.getStorageSync(keyArr[index])
  }
  uni.clearStorageSync()
  for (const key in obj) {
    uni.setStorageSync(key, obj[key])
  }
}

/**
 * 路径跳转 navigateTo
 * @param {string} path         要跳转的路径
 * @param {boolean?} needToken  是否需要 token
 * @param {boolean?} directJump 如果需要 token 并且没有 token 时是否直接跳转到登录页，否则会给出提示，点击确定后才会跳转到登录页
 */
util.navTo = (path, needToken, directJump) => {
  if (needToken && !util.getToken()) {
    const loginPath = '/pages/login/role'
    if (directJump) {
      uni.navigateTo({ url: loginPath })
    } else {
      uni.showModal({
        title: '提示',
        content: '暂未登录，是否前往登录？',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({ url: loginPath })
          } else if (res.cancel) {
          }
        },
      })
    }
  } else {
    uni.navigateTo({ url: path })
  }
}
util.redirectTo = (path, needToken, directJump) => {
  if (needToken && !util.getToken()) {
    const loginPath = '/pages/login/role'
    if (directJump) {
      uni.redirectTo({ url: loginPath })
    } else {
      uni.showModal({
        title: '提示',
        content: '暂未登录，是否前往登录？',
        success: (res) => {
          if (res.confirm) {
            uni.redirectTo({ url: loginPath })
          } else if (res.cancel) {
          }
        },
      })
    }
  } else {
    uni.redirectTo({ url: path })
  }
}
util.switchTab = (path) => uni.switchTab({ url: path })

/**
 * 预览图片
 * @param {Array<String>} urls
 * @param {String | Number} current
 */
util.previewImage = (urls, current) => {
  urls = urls.map((url) => util.addDomain(url))
  // console.log('预览图片', urls, current)
  // https://uniapp.dcloud.net.cn/api/media/image.html#unipreviewimageobject
  uni.previewImage({ urls, current })
}

/**
 * 复制
 * @param {string} str
 */
util.copyStr = (str) => {
  uni.setClipboardData({ data: str })
}

/**
 * 拨打电话
 * @param {string} phoneNumber
 */
util.makePhoneCall = (phoneNumber) => {
  if (!phoneNumber) return uni.showToast({ title: '电话有误', icon: 'none' })
  uni.makePhoneCall({ phoneNumber })
}

/**
 * 给链接加域名
 * @param {string} url
 */
util.addDomain = (url) => {
  if (!url || typeof url !== 'string') return url
  if (url.startsWith('http')) return url

  return config.baseURL + url
}

/**
 * 去掉链接中的域名
 * @param {string} url
 */
util.removeDomain = (url) => {
  if (!url || typeof url !== 'string') return url
  if (!url.startsWith('http')) return url

  const domain = url.split('//')[1].split('/')[0]
  const localPath = url.split('//')[1].split(domain)[1]
  return localPath
}

/**
 * 调用接口获取登录凭证（code）。
 * https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
 */
util.getLoginCode = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin', //使用微信登录
      success: async (res) => {
        // console.log('uni.login', res)
        if (res.code) {
          resolve(res.code)
        } else {
          reject(res)
          uni.showToast({ title: res.errMsg, icon: 'none' })
        }
      },
      fail: (err) => {
        reject(err)
        uni.showToast({ title: err.errMsg, icon: 'none' })
      },
    })
  })
}

export default util
